#!/usr/bin/python
# -*- coding: utf-8 -*-

import subprocess, math, os

import sqlite3 as sdb

def create_db(db_file):
	conn = sdb.connect(db_file)
	curs = conn.cursor()
	curs.execute	('''create table archive (
						dateTime INTEGER NOT NULL UNIQUE PRIMARY KEY,
						adc_vb_f REAL,
						adc_va_f REAL,
						adc_vl_f REAL,
						adc_ic_f REAL,
						adc_il_f REAL,
						T_hs REAL,
						charge_state INTEGER,
						Power_out REAL,
						Ahc_daily REAL,
						Ahl_daily REAL
						)'''
			)

import time
db_path = '/home/tom/logs/'
db_filename = time.strftime('sunsaver_%Y_%m.sdb')

db_file = db_path + db_filename

exists = os.path.isfile(db_file)

if not exists:
	print "Database file not found! Creating..."
	create_db(db_file)

conn = sdb.connect(db_file)
curs = conn.cursor()
curs.execute("select * from archive")

ss_cmd="/home/tom/siweather/scripts/update_sunsaver"
test_file = "/home/tom/sunsaver.temp"

variables = 	[
		['adc_vb_f','V',float('nan')],
		['adc_va_f','V',float('nan')],
		['adc_vl_f','V',float('nan')],
		['adc_ic_f','A',float('nan')],
		['adc_il_f','A',float('nan')],
		['T_hs','C',float('nan')],
		['charge_state','',float('nan')],
		['Power_out','W',500.0],
		['Ahc_daily','Ah',float('nan')],
		['Ahl_daily','Ah',float('nan')] 
		]

good = 0
attempts = 0

while not good and attempts < 5:
	
	attempts = attempts + 1
	#output = subprocess.Popen(["cat", test_file], stdout=subprocess.PIPE).communicate()[0]
	output = subprocess.Popen([ss_cmd], stdout=subprocess.PIPE).communicate()[0]
	
	split = output.split('\n')

	values = [ int(round(time.time())) ]
	for i in split:
		for j in variables:
			if j[0] == i.split(' ')[0]:
				j[2] = float( i.split(' ')[2] )
				values.append(j[2])
	good = variables[7][2] < 150.0
	if not good: time.sleep(3)

if good:
	values[7] = int(values[7])

	insert = 'insert into archive values (%i, %f, %f, %f, %f, %f, %f, %i, %f, %f, %f)' % ( values[0], values[1], values[2], 
				values[3], values[4], values[5], 
				values[6], values[7], values[8], 
				values[9], values[10] )

	curs.execute(insert)
	conn.commit()